/*
 * 
 * Libman
 * 
 * Daniel Kaufmann, Martin Lang, Simon Moosbrugger,
 * Stefan Mayer, Stephan Halbeisen
 * 
 */
package application.controller.server;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import middleware.datacontainer.searchclient.ClientContainer;
import model.Client;
import model.dao.DAOFactory;
import application.exceptions.InsufficientClientRightsException;
import application.exceptions.SessionException;
import application.exceptions.SessionException.InvalidIpException;
import application.exceptions.SessionException.SessionDoesNotExistException;
import application.exceptions.SessionException.SessionExpiredException;

/**
 * The Class UseCaseControllerClientSearch.
 */
public class UseCaseControllerClientSearch extends AbstractUseCaseController {
	public UseCaseControllerClientSearch() {
		super();
		
		if(_allowedRoles == null){
			String[] roles = {"Admin", "Employee"};
			_allowedRoles = Arrays.asList(roles);
		}
	}
	
	/**
	 * Search client.
	 * 
	 * @param searchPattern
	 *            the search pattern
	 * @return the array list
	 * @throws InsufficientClientRightsException 
	 * @throws InvalidIpException 
	 * @throws SessionDoesNotExistException 
	 * @throws SessionExpiredException 
	 */
	public ArrayList<ClientContainer> searchClient(String sessionId, String ip, String searchPattern) throws SessionException, InsufficientClientRightsException {
		checkLogin(sessionId, ip);
		
		ArrayList<Client> exMediums = new ArrayList<Client>();

		String[] searchPart = searchPattern.trim().split(" ");

		for (String part : searchPart) {
			Client c = new Client();
			c.setFirstName(part);
			c.setLastName(part);
			exMediums.add(c);
		}

		List<Client> clients = DAOFactory.getInstance().getClientDAO()
				.searchClient(exMediums, 100);
		ArrayList<ClientContainer> list = new ArrayList<ClientContainer>();

		for (Client m : clients) {
			list.add(new ClientContainer(m.getId(), m.getFirstName(), m.getLastName()));
		}
		return list;
	}
}
